package net.form.processing;

import java.awt.Color;

public class Hildich extends AbstractImageCommand{

	private static int blanco = (new Color(255, 255, 255)).getRGB();
	private static int negro = (new Color(0, 0, 0)).getRGB();
	private HSVRangeGridAndBackground hsvRangeGridAndBackground;
	private Image originalImage;

	public Hildich(Image image,HSVRangeGridAndBackground hsvRangeGridAndBackground, Image originalImage) {
		super(image);
		this.hsvRangeGridAndBackground=hsvRangeGridAndBackground;
		this.originalImage = originalImage;
	}

	public Image execute() {
		if (getImage() != null) {
			Image imageGrid = new Image(getImage().getWidth(),
					getImage().getHeight());
			imageGrid = (Image) getImage();
			while (haveGrid(imageGrid)) {
				Erode erode = new Erode(imageGrid);
				imageGrid = erode.execute();
				if(haveGrid(imageGrid)){
					Opening opening = new Opening(imageGrid);
					imageGrid = opening.execute();	
				}
			}
			return imageGrid;
		}
		return null;
	}

	private boolean haveGrid(Image imageGrid) {
		boolean haveGrid = false;
		if (imageGrid != null) {

			for (int y = 0; y < imageGrid.getHeight(); y++)
				for (int x = 0; x < imageGrid.getWidth(); x++) {
					try {
						if (!isFondo(imageGrid.getRGB(x, y), imageGrid)) {
							Color color = new Color(originalImage.getRGB(x, y));
							if (hsvRangeGridAndBackground.isInRangeGrid(color)) {
								System.out.println("Es grilla  x: " + x
										+ ", y: " + y);
								return false;
							}
						}
					} catch (Exception e) {
						System.out.println("x: " + x + ", y: " + y);
						e.printStackTrace();
					}
				}
		}
		return haveGrid;
	}

	public boolean isFondo(int colorPixel, Image image) {
		if (image != null)
			return colorPixel == negro;
		return false;
	}

	public String getCommandName() {
		return null;
	}

}
